package controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.SysRole;
import pojo.SysUser;
import service.SysRoleService;
import service.SysUserService;
import utils.Constants;
import utils.FileUpload;
import utils.PageSupport;
import web.converter.BaseController;

import jakarta.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/sys/user")
@Scope("prototype")
public class SysUserController extends BaseController {
    private static final Logger log=Logger.getLogger(SysUserController.class);

    @Resource(name = "sysUserService")
    private SysUserService userService;
    @Resource(name = "sysRoleService")
    private SysRoleService roleService;



    // 跳转到登录页面
    @RequestMapping("/toLogin")
    public String login(HttpSession session){
        return "login";
    }

    // 退出登录
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        SysUser sysUser=(SysUser) session.getAttribute(Constants.USER_SESSION);
        if(sysUser!=null){
            System.out.println("session中存在用户信息，跳转到登录页面");
            session.invalidate();
        }
        return "redirect:/sys/user/toLogin";
    }

    @RequestMapping("/login")
    public String doLogin(@RequestParam("account")String account, @RequestParam("password")String password,
                          HttpServletRequest request, HttpSession session){
        log.debug("登录方法");
        List<SysUser> doUser=userService.queryByAccount(account);
        if(doUser.size()==0){
            request.setAttribute("error","用户名不存在！");
            return "login";
        }
        SysUser sysUser=userService.login(account,password);
        if(sysUser!=null){
            session.setAttribute(Constants.USER_SESSION,sysUser);
            return "redirect:/sys/user/toMain";
        }else {
            request.setAttribute("error","密码不正确！");
            return "login";
        }
    }

    @RequestMapping("/toMain")
    public String toMain(HttpSession session){
        if(session.getAttribute(Constants.USER_SESSION)==null){
            return "redirect:/sys/user/toLogin";
        }
        return "frame";
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e,HttpServletRequest request){
        System.out.println("捕获到异常"+e.getMessage());
        request.setAttribute("e",e);
        return "sysError";
    }

    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account,@RequestParam String password){
        System.out.println(account+password);
        SysUser user=userService.login(account,password);
        if(user!=null){
            throw new RuntimeException("用户名或密码不正确，跳转到错误页面！");
        }
        return "redirect:/sys/user/toMain";
    }

    @GetMapping("/list")
    public String getUserList(Model model,String queryRealName,Integer queryRoleId,@RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysUser> userList=null;
        try{
            int pageSiz=Constants.pageSize;
            int totalCount=userService.getUserCount(queryRealName==null?null:queryRealName,queryRoleId==null?0:queryRoleId);
            PageSupport pages=new PageSupport();
            pages.setNumberPage(pageSiz);
            pages.setCurrentPage(pageIndex-1);
            pages.setTotalPage(totalCount);

            int totalPageCount=pages.getTotalPage();
            if(pageIndex>totalPageCount){
                pageIndex=totalCount;
                throw new RuntimeException("页面不正确");
            }
            userList=userService.getUserList(queryRealName,queryRoleId==null?0:queryRoleId,pages.getCurrentPage()*pageSiz,pages.getNumberPage());
            model.addAttribute("userList",userList);
            List<SysRole> roleList=roleService.getRoleList();
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            // 总页数
            model.addAttribute("totalPageCount",totalPageCount);
            // 总记录数
            model.addAttribute("totalCount",totalCount);
            // 当前页数
            model.addAttribute("currentPageNo",pageIndex);
        }catch (Exception e){
            log.error("查询用户列表失败",e);
            return "redirect:/sys/user/toSysError";
        }
        return "sysUser/list";
    }

    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }

    @RequestMapping(value = "/toAdd")
    public String toAdd(HttpServletRequest request){
        return "sysUser/add";
    }


    @GetMapping("/view/{id}")
    public String view(@PathVariable String id,Model model){
        SysUser sysUser=userService.getUserById(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/view";
    }

    @GetMapping("/toUpdate/{id}")
    public String toUpdate(Model model,@PathVariable String id,HttpSession session){
        log.info("跳转到修改用户页面,id:"+id);
        SysUser sysUser=userService.getUserById(id);
        sysUser.setIdPicPath(FileUpload.existsPath(sysUser.getIdPicPath(),session));
        sysUser.setWorkPicPath(FileUpload.existsPath(sysUser.getWorkPicPath(),session));
        model.addAttribute("sysUser",sysUser);
        return "sysUser/update";
    }

    @PostMapping("/update")
    public String modifySave(SysUser sysUser,MultipartFile idPicPath,MultipartFile workPicPath,
                             HttpSession session,HttpServletRequest request){
        log.info("修改用户信息:"+sysUser);
        String uploadPath=session.getServletContext().getRealPath(Constants.UPLOAD_PATH);
        SysUser create=(SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setUpdatedUserId(create.getId());
        sysUser.setUpdatedTime(String.valueOf(new Date()));
        if (idPicPath!=null){
            // 提取文件上传的方法
            String idPic = FileUpload.multipartFileUpload(uploadPath, idPicPath);
            // Web访问的路径（不是文件上传的磁盘位置）
            if (idPic == null) {
                request.setAttribute("error","文件有问题");
                return "sysUser/update";
            }
            log.debug("idPic:"+idPic);
            // 设置身份证照片路径
            sysUser.setIdPicPath(idPic);
        }
        if (workPicPath!=null){
            // 提取文件上传的方法
            String getWorkPic = FileUpload.multipartFileUpload(uploadPath, workPicPath);
            // Web访问的路径（不是文件上传的磁盘位置）
            if (getWorkPic == null) {
                request.setAttribute("error","文件有问题");
                return "sysUser/update";
            }
            log.debug("getWorkPic:"+getWorkPic);
            // 设置身份证照片路径
            sysUser.setWorkPicPath(getWorkPic);
        }
        if(userService.update(sysUser)){
            return "redirect:/sys/user/list";
        }else {
            return "sysUser/update";
        }
    }


    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "attachs",required = false)MultipartFile[] attachs){
        log.info("添加用户信息,name:"+sysUser.getRealName());
        String idPic=null;
        String workPic=null;
        String errorInfo=null;
        boolean flag=true;

        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if(i==0){
                    errorInfo="uploadFileError";
                }else if(i==1){
                    errorInfo="uploadWpError";
                }
                String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
                log.info("uploadFile path======>" + path);
                log.info("上传文件路径:" + path+"  |");
                String oIdFileName = attach.getOriginalFilename(); // 原文件名
                log.info("原文件名:" + oIdFileName+"  |");
                String suffix = FilenameUtils.getExtension(oIdFileName); // 原文件后缀
                log.info("原文件后缀:" + suffix+"  |");
                int filesize = 50000000;
                if (attach.getSize() > filesize) { // 上传大小不得超过500kB
                    request.setAttribute("uploadFileError", "*上传文件不得大于500kB");
                    flag=false;
                } else if (suffix.equalsIgnoreCase("jpg")
                        || suffix.equalsIgnoreCase("png")
                        || suffix.equalsIgnoreCase("jpeg")
                        || suffix.equalsIgnoreCase("pneg")) { // 上传图片格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        System.out.println("图片存储路径不存在，创建路径:" + path);
                        targetFile.mkdirs();
                    }

                    // 保存
                    try {
                        System.out.println("targetFile"+targetFile);
                        System.out.println("fileName"+fileName);
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (IllegalStateException | IOException e) {
                        e.printStackTrace();
                        request.setAttribute("uploadFileError", "*上传失败");
                        flag=false;
                    }
                    if(i==0){
                        idPic = File.separator + "statics" + File.separator + "uploadFiles" + File.separator + fileName;
                    }else if(i==1){
                        workPic=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+fileName;
                    }
                    log.info("idPicPath:" + idPic);
                    log.info("workPicPath:" + workPic);
                } else {
                    request.setAttribute(errorInfo, "*上传文件格式不正确");
                    flag=false;
                }
            }
        }
        sysUser.setCreateUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
        sysUser.setIdPicPath(idPic);
        sysUser.setWorkPicPath(workPic);
        if (userService.add(sysUser) && flag) {
            return "redirect:/sys/user/list";
        } else {
            return "sysUser/add";
        }
    }

    @GetMapping("/userExist")
    @ResponseBody
    public Object userExist(@RequestParam String account) throws IOException {
        System.out.println("account:"+account);
        Map<String,Object> map=new HashMap<>();
        if(userService.userExist(account)>0){
            map.put("exist",1);
        }else{
            map.put("exist",0);
        }
        return JSON.toJSONString(map);
    }

    @GetMapping(value = "/{id}/view")
    @ResponseBody
    public Object view(@PathVariable String id){
        log.info("根据id查询用户信息id："+id+"  |");
        SysUser user=null;
        if(id==null||id.equals("")){
            return "nodata";
        }else {
            try {
                user=userService.getUserById(id);
                log.info("用户信息转换为JSON格式："+user+"   |");
            }catch (Exception e){
                e.printStackTrace();
                return "failed";
            }
            return user;
        }
    }

    @DeleteMapping("/del/{userid}")
    @ResponseBody
    public Object delUser(@PathVariable String userid, HttpSession session){
        Map<String,String> map= new HashMap<>();
        System.out.println("删除用户id:"+userid);
        SysUser sysUser= userService.getUserById(userid);

        List<String> paths=new ArrayList<>();
        if(sysUser.getIdPicPath()!=null){
            paths.add((String) sysUser.getIdPicPath());
        }
        if (sysUser.getWorkPicPath()!=null) {
            paths.add((String) sysUser.getWorkPicPath());
        }
        for (int i = 0; i < paths.size(); i++) {
            String path=session.getServletContext().getRealPath(paths.get(i));
            File file=new File(path);
            if(file.exists()){
                System.out.println("删除图片:"+path);
                file.delete();
            }
        }
        if(userService.delete(Integer.parseInt(userid))){
            map.put("delResult","true");
        }else{
            map.put("delResult","false");
        }
        return map;
    }


}
